package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class StorageTCCImpl implements StorageTCC {
    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override   //预留数据
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        Storage storage = storageMapper.SelectById(productId);
        if(storage.getResidue()<count){
            throw new RuntimeException("库存不足了");

        }
        storageMapper.updateResidueToFrozen(productId, count);
        return false;
    }
    @Transactional
    @Override   //提交事务方法
    public boolean commit(BusinessActionContext ctx) {
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count= Integer.valueOf(ctx.getActionContext("count").toString());

        storageMapper.updateFrozenToUsed(productId, count);
        return true;
    }
    @Transactional
    @Override  //回滚事务方法
    public boolean rollback(BusinessActionContext ctx) {
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count= Integer.valueOf(ctx.getActionContext("count").toString());

        storageMapper.updateFrozenToResidue(productId, count);
        return true;
    }
}
